<template>
  <table class="my-chart-item-table">
    <tr class="my-row-height">
      <td class="my-label">Name:</td>
      <td class="my-value">
        <q-input
          dense
          outlined
          type="text"
          v-model.lazy="myName"
          @update:model-value="refreshData"
        />
      </td>
    </tr>
    <tr class="my-row-height">
      <td class="my-label">Color:</td>
      <td class="my-value">
        <ColorInput
          v-model:color="myColor"
          @update:color="refreshData"
        />
      </td>
    </tr>
  </table>
</template>

<script lang="ts">
import { defineComponent, ref, toRefs, onMounted, watch } from  'vue';
import ColorInput from './ColorInput.vue';

export default defineComponent({
  name: 'ChartItem',
  components: {
    ColorInput
  },

  props: {
    chart: {
      type: String,
      default: () => { return '[温度][#ffcc00]' }
    }
  },

  emits: ['update:chart'],
  setup (props, context) {
    //解构
    const {
      chart
    } = toRefs(props);

    //响应数据
    let myName = ref('');
    let myColor = ref('');

    //截取函数
    const parseStr = (sType: string, str: string) => {
      if (sType === 'name') {
        return str.substring(str.indexOf('[') + 1, str.indexOf(']'));
      } else if (sType === 'color') {
        return str.substring(str.lastIndexOf('[') + 1, str.lastIndexOf(']'));
      }

      return '';
    }

    //合成字符串
    const composeStr = () => {
      let s = '[' + myName.value + '][' + myColor.value + ']';
      return s;
    }

    //初始化
    const init = () => {
      myColor.value = parseStr('color', chart.value);
      myName.value = parseStr('name', chart.value);
    }

    //刷新数据
    const refreshData = () => {
      let str = composeStr();
      context.emit('update:chart', str);
    }

    //检测数据变化
    watch(() => chart, () => {
      init();
    }, { deep: true });

    //挂载组件
    onMounted(() => {
      init();
    })

    return {
      myName,
      myColor,
      refreshData
    };
  }
});

</script>

<style lang="scss" scoped>
.my-chart-item-table {
  .my-row-height {
    line-height: 35px;
  }
  .my-label {
    text-align: left;
    width: 60px;
  }
  .my-value {
    text-align: left;
    width: 220px;
  }
}
</style>
